package com.lj.bruth.controller;

import com.alibaba.fastjson.JSON;
import com.lj.bruth.config.ElasticSearchConfig;
import com.lj.bruth.model.ESUser;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.lucene.index.Terms;
import org.elasticsearch.action.DocWriteResponse;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;;
import org.springframework.web.bind.annotation.*;


import java.io.IOException;
import java.util.*;

import static jdk.nashorn.internal.objects.NativeRegExp.source;

@Controller
@RequestMapping(value = "/es")
public class ArticleController {

    @Autowired
    private RestHighLevelClient client;


    //报错应该是版本的问题  id是给我每一条添加一个编号 对应数据中的 _id
    @RequestMapping(value = "/search",method = RequestMethod.GET)
    @ResponseBody
    public String query(@RequestParam("index")String index,@RequestParam("userName")String userName,@RequestParam("dataByuUerName")String dataByuUerName) throws IOException{
        // 1. 构建检索请求
        SearchRequest searchRequest = new SearchRequest();
        // 2. 指定检索索引
        searchRequest.indices(index);
        // 3.1 指定DSL内容
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        // 3.1.1 构建query条件
        searchSourceBuilder.query(QueryBuilders.existsQuery(userName).queryName(dataByuUerName));  // 匹配address包含mill的雇员
        // 3.1.2 构建聚合条件
        // 3. 创建检索条件 用于构建DSL语言
        searchRequest.source(searchSourceBuilder);

        // 4. 执行检索
        SearchResponse searchResponse = client.search(searchRequest, ElasticSearchConfig.COMMON_OPTIONS);
        // 5. 分析结果
        // 5.1 获取所有查到的记录
        SearchHits hits = searchResponse.getHits();
        // 5.2 获取所有命中的记录
        SearchHit[] searchHits = hits.getHits();
        for (SearchHit hit : searchHits) {
            System.out.println(hit.getId());
            System.out.println(hit.getSourceAsMap());
        }

        // 5.3 获取分析（聚合）信息
        Aggregations aggregations = searchResponse.getAggregations();
        Terms terms = aggregations.get("age");
//        terms
//        terms.getBuckets().forEach(item ->
//                System.out.println("年龄："+ item.getKeyAsString() + "  total：" + item.getDocCount()));
      return null;
    }

    /**
     * GET检索  id是给我每一条添加一个编号 对应数据中的 _id
     */
    @RequestMapping(value = "/getData",method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> getData(@RequestParam("index") String index,@RequestParam("id") String id) throws IOException{
        // 参数一：索引名
        // 参数二：id
        GetRequest request = new GetRequest(index,id);
        //异步 和 GetRequest没有太大区别
        //GetAsyncSearchRequest getAsyncSearchRequest = new GetAsyncSearchRequest(id)
        GetResponse getResponse = client.get(request, ElasticSearchConfig.COMMON_OPTIONS);
        Map<String, Object> sourceAsMap = getResponse.getSourceAsMap();
        return sourceAsMap;
        /**
         * {
         *     "gender": "男",
         *     "userName": "哈雷为",
         *     "age": 18
         * }
         */
    }


    /**
     * 创建索引并添加数据  id是给我每一条添加一个编号 对应数据中的 _id
     * @return
     */
    @RequestMapping(value = "/save",method = RequestMethod.POST)
    @ResponseBody
    public IndexResponse save(@RequestParam("index")String index, @RequestParam("id") String id,@RequestBody ESUser esUser){
        //索引名称
        IndexRequest indexRequest = new IndexRequest(index);
        //相同id会数据覆盖
        indexRequest.id(id);
        //ESUser user = new ESUser("哈雷为", "男", 18);
        indexRequest.source(JSON.toJSONString(esUser), XContentType.JSON);
        //执行操作
        IndexResponse indexResponse = null;
        try {
            indexResponse = client.index(indexRequest, ElasticSearchConfig.COMMON_OPTIONS);
        } catch (IOException e) {
        }

        //提取有用的操作数据
        System.out.println(indexResponse);
        return indexResponse;
        /**
         * {
         *   "took" : 14,
         *   "timed_out" : false,
         *   "_shards" : {
         *     "total" : 5,
         *     "successful" : 5,
         *     "skipped" : 0,
         *     "failed" : 0
         *   },
         *   "hits" : {
         *     "total" : 2,
         *     "max_score" : 0.5753642,
         *     "hits" : [
         *       {
         *         "_index" : "users",
         *         "_type" : "_doc",
         *         "_id" : "2",
         *         "_score" : 0.5753642,
         *         "_source" : {
         *           "age" : 27,
         *           "gender" : "明教",
         *           "userName" : "五散人"
         *         }
         *       },
         *       {
         *         "_index" : "users",
         *         "_type" : "_doc",
         *         "_id" : "3",
         *         "_score" : 0.5753642,
         *         "_source" : {
         *           "age" : 71,
         *           "gender" : "明教3333",
         *           "userName" : "五散人"
         *         }
         *       }
         *     ]
         *   }
         * }
         */
    }

    /**
     * 删除索引和对应id的数据
     * @return
     */
    @RequestMapping(value = "/deleteIndex",method = RequestMethod.POST)
    @ResponseBody
    public String deleteData(@RequestParam("index")String index,@RequestParam("id")String id){
        //执行操作
        DeleteResponse deleteResponse = null;
        DeleteRequest delete = new DeleteRequest(index,id);
        try {
           deleteResponse = client.delete(delete, ElasticSearchConfig.COMMON_OPTIONS);
        } catch (IOException e) {
        }
        String s = deleteResponse.getResult().toString();
        //提取有用的操作数据
        System.out.println(deleteResponse);
        return s;
    }

    /**
     * 创建索引并添加数据
     * @return
     */
//    @RequestMapping(value = "/putData",method = RequestMethod.PUT)
//    @ResponseBody
//    public DocWriteResponse.Result putData(@RequestParam("index")String index,@RequestParam("id")String id)throws IOException{
//        Map<String,Object> map = new HashMap<>();
//        map.put("userName","组长");
//        UpdateRequest updateRequest = new UpdateRequest(index, "text", id).doc();
//        UpdateResponse update = client.update(updateRequest, ElasticSearchConfig.COMMON_OPTIONS);
//        DocWriteResponse.Result result = update.getResult();
//        return result;
//    }

    /**
     *
     * @param index
     * @param id
     * @param esUser
     * @return 插入批量数据 现在情况是请求报错，因为docker中版本太低，升高了就行！！！！！！
     */
    @RequestMapping(value = "/bulk",method = RequestMethod.POST)
    @ResponseBody
    public BulkResponse bulk(@RequestParam("index")String index) {
        //索引名称
        List<Map<String, Object>> list = new ArrayList<>();
        BulkResponse bulk = null;
        BulkRequest request = new BulkRequest();
        for (int i = 0; i < 10; i++) {
            Map<String, Object> map = new HashMap<>();
            map.put("address", "四川省成都市犀浦镇百草路" + 12 + i + "号");
            map.put("gender", "男");
            map.put("user_name", RandomStringUtils.randomAlphanumeric(10));
            map.put("post_date", new Date());
            IndexRequest indexRequest = new IndexRequest(index);
            //indexRequest.id(String.valueOf(new Date()));
            indexRequest.source(map);
            request.add(indexRequest);
        }
        try {
            bulk = client.bulk(request, ElasticSearchConfig.COMMON_OPTIONS);
            if (bulk.status().getStatus() == 200) {
                System.out.println("存储成功");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bulk;

    }
}
